define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var pageIndex = 1;
    var pageSize = 20;
    var firstTime = true;

    var modifyPrice = {
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "批量改价") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initTable();
            this.initValidator();
            this.getplatform();
            this.bindEvent();
        },
        /*
         初始化表格
         */
        initTable: function (shopId) {
            var self = this;
            shopTable = $("#goods_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/shop/freight/CRM/searchFreight'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if(firstTime){
                        firstTime = false;
                        return;
                    }
                    var _url = CRM.getOuterUrl('/outway/sync/item/spu/price/page');
                    var dataString = {
                        "isp": $("#platform").val(),
                        "barcode": $('#barcode').val(),
                        "pageNo": aoData[3].value / 30 + 1,
                        "pageSize": 30,
                        "time": new Date().getTime()
                    };
                    CRM.request({
                        "type": 'GET',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.responseCode && req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = req.entry.totalCount;
                                    resultData.iTotalRecords = req.entry.totalCount;
                                    for (var length in req.entry.result) {
                                        resultData.aaData.push([
                                            req.entry.result[length].ispName,
                                            req.entry.result[length].spuId,
                                            CRM.htmlEncode(req.entry.result[length].mainImageUrl),
                                            req.entry.result[length].barcode,
                                            CRM.htmlEncode(req.entry.result[length].name),
                                            CRM.htmlEncode(req.entry.result[length].property),
                                            req.entry.result[length].unit,
                                            req.entry.result[length].brand,
                                            req.entry.result[length].price,
                                            req.entry.result[length]
                                        ]);
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        },
                        error: function (e) {
                            //请求出错处理
                            CRM.showDialog("获取商品列表,请求服务异常！");

                        }
                    });
                },
                "aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [
                    {
                        "sTitle": "平台",
                        "bSortable": true
                    },
                    {
                        "sTitle": "spuid",
                        "bSortable": true
                    },
                    {
                        "sTitle": "图片",
                        "bSortable": true,
                        "mRender": function (data) {
                            var html = '<img src="' + "http://imgsize.52shangou.com/img/" + data + '@75w">';
                            return html;
                        }
                    },
                    {
                        "sTitle": "条码",
                        "bSortable": true
                    },
                    {
                        "sTitle": "spu名称",
                        "bSortable": true
                    },
                    {
                        "sTitle": "规格",
                        "bSortable": true
                    },
                    {
                        "sTitle": "单位",
                        "bSortable": true
                    },
                    {
                        "sTitle": "品牌",
                        "bSortable": true,
                    },
                    {
                        "sTitle": "价格",
                        "bSortable": true,
                        "mRender": function (data, type, row) {
                            return data / 100;
                        }
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": false,
                        "mRender": function (data) {
                            var html = '<button type="button" class="btn btn-info" onclick="javascript:showModifyPriceModal(\'' + data.barcode + '\')">改价</button>';
                            html+= '<button type="button" class="btn btn-warning" onclick="javascript:recover(\'' + data.barcode + '\')">恢复</button>';
                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /*
        获取平台类型
         */
        getplatform: function(){
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/ispList"),
                "dataType": "json",
                contentType: "application/json",
                "data": {
                    "time" : new Date().getTime()
                },
                "success": function (req) {
                    if (req.status){
                        var arr = [];
                        $.each(req.entry, function(index, item) {
                            arr.push("<option value='" + item.id + "'>" + item.name + "</option>");
                        });
                        $("#platform").html(arr.join(''));
                        firstTime = false;
                        self.doSearch();
                    }else {
                        CRM.showDialog(req.message);
                    }
                },
                error: function (e) {
                    //请求出错处理
                    CRM.showDialog("获取平台列表,请求服务异常！");
                }
            });
        },
        /*
         获取改价过的列表
         */
        doSearch: function (pageNo) {
            $('#goods_table').DataTable().ajax.reload();
        },
        /*
        批量改价
         */
        modifyPrice: function (barcode,isp,price) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/outway/sync/item/spu/price/modify"),
                "dataType": "json",
                contentType: "application/json",
                xhrFields: {
                    withCredentials: true
                },
                "data": {
                    "isp": isp,
                    "barcode": barcode,
                    "price": price*1000/10,
                    "time": new Date().getTime()
                },
                "success": function (req) {
                    if(req.status){
                        $('#modifyPrice_dialog').modal("hide");
                        self.doSearch();
                    }
                    CRM.showDialog(req.message);
                },
                error: function (e) {
                    //请求出错处理
                    CRM.showDialog("执行改价操作,请求服务异常！");
                }

            });
        },

        /*
        改价模态框显示
         */
        showModifyPriceModal: function (barcode) {
            $('#dialog_barcode').val(barcode);
            $('#modifyPrice_dialog').modal('show');
        },
        /*
        通过 模块框 改价
         */
        dialog_modifyPrice: function () {
            var self = this;
            $("#dialog_form").data('bootstrapValidator').validate();
            if ($("#dialog_form").data('bootstrapValidator').isValid()) {
                self.modifyPrice($('#dialog_barcode').val(), $('#platform').val(), $('#dialog_price').val());
            }
        },
        /*
        通过 “输入条码” 改价
         */
        barcode_modifyPrice: function(){
            var self = this;
            $("#func-area").data('bootstrapValidator').validate();
            if ($("#func-area").data('bootstrapValidator').isValid()) {
                self.modifyPrice($('#barcode').val(), $('#platform').val(), $('#price').val());
            }
        },
        /*
        改价恢复
         */
        recover:function (barcode) {
            var self = this;
            if(confirm("确认恢复成闪电购平台价格？")) {
                CRM.request({
                    "type": 'GET',
                    "url": CRM.getOuterUrl("/outway/sync/item/spu/price/reset"),
                    "dataType": "json",
                    contentType: "application/json",
                    xhrFields: {
                        withCredentials: true
                    },
                    "data": {
                        "isp": $('#platform').val(),
                        "barcode": barcode,
                        "time": new Date().getTime()
                    },
                    "success": function (req) {
                        if (req.status) {
                            self.doSearch();
                        }
                        CRM.showDialog(req.message);
                    },
                    error: function (e) {
                        //请求出错处理
                        CRM.showDialog("执行恢复改价操作,请求服务异常！");
                    }

                });
            }
        },
        bindEvent: function () {
            var self = this;
            //点击外店按钮搜索
            $("#searchBtn").on('click', function () {
                self.doSearch();
            });
            //批量改价
            $("#modifyPriceBtn").on('click', function () {
                self.barcode_modifyPrice();
            });
            //监听平台变化
            $('#platform').change(function () {
                self.doSearch();
            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#dialog_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    dialog_barcode: {
                        message: 'error',
                        validators: {
                            notEmpty: {
                                message: '条码不得为空'
                            }
                        }
                    },
                    dialog_price: {
                        message: 'error',
                        validators: {
                            notEmpty: {
                                message: '价格不得为空'
                            },
                            regexp: {
                                regexp: /^\d+(\.\d{1,2})?$/,
                                message: '请输入数字'
                            }
                        }
                    }
                }
            });
            $('#func-area').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    barcode: {
                        message: 'error',
                        validators: {
                            notEmpty: {
                                message: '条码不得为空'
                            }
                        }
                    },
                    price: {
                        message: 'error',
                        validators: {
                            notEmpty: {
                                message: '价格不得为空'
                            },
                            regexp: {
                                regexp: /^\d+(\.\d{1,2})?$/,
                                message: '请输入数字'
                            }
                        }
                    }
                }
            });
        }
    };

    window.showModifyPriceModal = modifyPrice.showModifyPriceModal;
    window.dialog_modifyPrice = $.proxy(modifyPrice.dialog_modifyPrice,modifyPrice);
    window.recover = $.proxy(modifyPrice.recover,modifyPrice);
    modifyPrice.init();

});